package it.webrules.deploymanager.core.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO Windows and MAC???
 * 
 * @author dometec
 *
 */
public class System {

	private static final Logger LOGGER = LoggerFactory.getLogger(System.class);

	private System() {
	}

	public static int execute(String cmd) throws IOException {
		return execute(cmd, null, true, false);
	}

	public static int execute(String cmd, Integer checkExitCode, boolean printoutput, boolean failsilently) throws IOException {

		if (checkExitCode == null)
			LOGGER.debug("Execute command '{}'.", cmd);
		else
			LOGGER.debug("Execute command '{}' and expect {}.", cmd, checkExitCode);

		// TODO gestire le altre piattaforme!

		ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", cmd);
		pb.redirectErrorStream(true);
		Process proc = pb.start();

		new ReadOutputProcess(proc, printoutput).start();
		int exitCode = 0;

		try {
			exitCode = proc.waitFor();
		} catch (InterruptedException e) {
			throw new IOException(e);
		}

		if (checkExitCode == null) {
			if (exitCode != 0 && !failsilently)
				LOGGER.warn("The execution of '{}' return a value != 0 ({})", cmd, exitCode);
		} else if (exitCode != checkExitCode)
			throw new IOException("The execution of '" + cmd + "' result is " + exitCode);

		return exitCode;

	}
}

class ReadOutputProcess extends Thread {

	private final Logger logger = LoggerFactory.getLogger(ReadOutputProcess.class);
	private final Process proc;
	private final boolean printoutput;

	public ReadOutputProcess(Process proc, boolean printoutput) {
		this.proc = proc;
		this.printoutput = printoutput;
	}

	@Override
	public void run() {

		try {

			BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			String line;
			while ((line = is.readLine()) != null) {
				if (printoutput)
					logger.info("Command OUTPUT: {}", line);
			}

		} catch (Exception e) {
			logger.error("Error reading output of process.", e);
		}

	}

}
